package agenda.util;

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

import agenda.dao.InterfazContactoDAO;

public abstract class ImportarExportarCSV {


	public static String[][] toArray(String arch, String separador, int campos) throws FileNotFoundException {
		ArrayList<String> al = new ArrayList<String>();
		Scanner sc = new Scanner(new File(arch));
		while (sc.hasNext()) {
			al.add(sc.nextLine());
		}
		sc.close();

		int cols = al.get(0).split(separador).length;
		String[][] resultado = new String[al.size()][cols];
		for (int i = 0; i < resultado.length; i++) {
			resultado[i] = al.get(i).split(separador, campos);
		}
		return resultado;
	}

	public static void fromArray(String arch, String separador, String[][] datos) throws IOException {
		
		if(datos==null || datos.length==0 || datos[0].length == 0) 
			return;
		
		PrintWriter pw = new PrintWriter(new FileWriter(arch));
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < datos.length; i++) {
			for (int j = 0; j < datos[0].length; j++) {
				sb.append(datos[i][j]+separador);
			}
			pw.println(sb.toString().substring(0, sb.toString().length()-1));
			sb = new StringBuilder();
		}
		pw.close();
	}
	
	public static void grabarObj(Object obj, String arch) throws IOException {
		ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(new File(arch)));
		oo.writeObject(obj);
		oo.close();
	}

	public static InterfazContactoDAO leerObj(String arch) throws IOException {
		ObjectInputStream oi = new ObjectInputStream(new FileInputStream(new File(arch)));
		InterfazContactoDAO cDAO=null;
		try {
			cDAO = (InterfazContactoDAO) oi.readObject();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		oi.close();
		return cDAO;
	}
}
